<template>
  <div>
    <el-table
      :data="tableList"  @select="rowSelect"
              @select-all="selectAll"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
    
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column
        label="字段名"
        prop="comments"
        align="center"
        :show-overflow-tooltip="true"
        width="90"
      />
      <!-- 是否显示列 -->
      <el-table-column prop="isDisplay" label="是否显示" width="180">
        <template slot="header">
          <div class="header-checkbox">
            <el-checkbox
              v-model="isDisplayAllSelected"
              :indeterminate="isDisplayIndeterminate"
              @change="handleIsDisplayAllChange"
            >全选</el-checkbox>
          </div>
        </template>
        <template slot-scope="scope">
          <el-checkbox
            v-model="scope.row.isDisplay"
             true-label="Y"
            false-label="N"
            @change="handleIsDisplayCheckChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>

      <!-- 是否必填列 -->
      <el-table-column prop="isRequired" label="是否必填" width="180">
        <template slot="header">
          <div class="header-checkbox">
            <el-checkbox
              v-model="isRequiredAllSelected"
              :indeterminate="isRequiredIndeterminate"
              @change="handleIsRequiredAllChange"
            >全选</el-checkbox>
          </div>
        </template>
        <template slot-scope="scope">
          <el-checkbox
            v-model="scope.row.isRequired"
            true-label="Y"
            false-label="N"
            @change="handleIsRequiredCheckChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <!-- 是否修改 -->
      <el-table-column prop="isModify" label="是否必填" width="180">
        <template slot="header">
          <div class="header-checkbox">
            <el-checkbox
              v-model="isModifyAllSelected"
              :indeterminate="isModifyIndeterminate"
              @change="handleIsModifyAllChange"
            >全选</el-checkbox>
          </div>
        </template>
        <template slot-scope="scope">
          <el-checkbox
            v-model="scope.row.isModify"
            true-label="Y"
            false-label="N"
            @change="handleIsModifyCheckChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
     
  </div>
</template>

<script>
// import { optionselect as getDictOptionselect } from "@/api/system/dict/type";
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
export default {
  props: {
    tableList: {
      type: Array,
      required: true
    },
    dataList: {
      type: Array,
      required: true
    },
  },
        data() {
                return {
                        tableVersion: 0,
                        haveTableData: [],
                        // 是否显示列全选状态
      isDisplayAllSelected: false,
      // 是否必填列全选状态
      isRequiredAllSelected: false,
      isModifyAllSelected: false
                        // dictOptions: []
                }
        },
        computed: {
        sortedData() {
      // 这里读取version用于强制刷新计算属性
      this.tableVersion
      return this.doSort()

    },
    isDisplayIndeterminate() {
      const selectedCount = this.tableList.filter(item => item.isDisplay=== "Y").length;
      return selectedCount > 0 && selectedCount < this.tableList.length;
    },
    isRequiredIndeterminate() {
      const selectedCount = this.tableList.filter(item => item.isRequired === "Y").length;
      return selectedCount > 0 && selectedCount < this.tableList.length;
    
    },
    isModifyIndeterminate() {
      const selectedCount = this.tableList.filter(item => item.isModify === "Y").length;
      return selectedCount > 0 && selectedCount < this.tableList.length;
    
    },
    selectedIsDisplay() {
      return this.tableList.filter(item => item.isDisplay=== "Y").map(item => item.isRequired).join(', ');
    },
    selectedIsRequired() {
      return this.tableList.filter(item => item.isRequired === "Y").map(item => item.isRequired).join(', ');
    },
    selectedIsModify() {
      return this.tableList.filter(item => item.isModify === "Y").map(item => item.isModify).join(', ');
    }
  },
  created() {
    // this.init()  
      /** 查询字典下拉列表 */
      // getDictOptionselect().then(response => {
      //   this.dictOptions = response.data;
      // });
      // this.haveTableData = this.dataList
    // console.log(this.tableList, this.dataList,'fdksl;fk')
  },
  watch: {
    tableList(newValue) {
      this.init() 

    }
  },
  methods: {
    // 是否显示列全选变化处理
    handleIsDisplayAllChange(val) {
      this.tableList.forEach(item => {
        item.isDisplay = val ? "Y" : "N";
      });
      this.isDisplayAllSelected = val; // 确保全选状态同步
      console.log(val,this.isDisplayAllSelected,this.tableList,'val')

    },
    
    // 是否必填列全选变化处理
    handleIsRequiredAllChange(val) {
      this.tableList.forEach(item => {
        item.isRequired = val ? "Y" : "N";
      });
      this.isRequiredAllSelected = 'Y'; // 确保全选状态同步
    },
    // 是否必填列全选变化处理
    handleIsModifyAllChange(val) {
      this.tableList.forEach(item => {
        item.isModify = val ? "Y" : "N";
      });
      this.isModifyAllSelected = 'Y'; // 确保全选状态同步
    },
    
    // 是否显示列单个选择变化处理
    handleIsDisplayCheckChange() {
      const selectedCount = this.tableList.filter(item => item.isDisplay).length;
      this.isDisplayAllSelected = selectedCount === this.tableList.length;
      this.isDisplayIndeterminate = selectedCount > 0 && selectedCount < this.tableList.length;
    },
    
    // 是否必填列单个选择变化处理
    handleIsRequiredCheckChange() {
      const selectedCount = this.tableList.filter(item => item.isRequired === "Y").length;
      console.log(selectedCount)
      this.isRequiredAllSelected = selectedCount === this.tableList.length;
      this.isRequiredIndeterminate = selectedCount > 0 && selectedCount < this.tableList.length;
    },
    // 是否必填列单个选择变化处理
    handleIsModifyCheckChange() {
      const selectedCount = this.tableList.filter(item => item.isModify === "Y").length;
      console.log(selectedCount)
      this.isModifyAllSelected = selectedCount === this.tableList.length;
      this.isModifyIndeterminate = selectedCount > 0 && selectedCount < this.tableList.length;
    },
    init() {
      console.log(this.tableList,'1')
    //   if(this.tableList){
    //      this.tableList = this.tableList.map(item => {
    //   return {
    //     ...item,
    //     isDisplay: 'N',
    //     isRequired: 'N'
    //   }
    //  })
    //   }
    

   this.tableList.forEach(row => {
       const isSelected = this.dataList.some(selected => selected.nickName === row.comments);
       if (isSelected) {
         this.$nextTick(() => {
        this.$refs.multipleTable.toggleRowSelection(row)
    })
       }
     });
    },
    handleSelectionChange(selection) {
      this.list = !selection.length;
    },
    rowSelect(selection, row) {
      // this.haveTableData = selection
      if (selection.length) {
        if (
          !this.haveTableData.some((item) => {
            return item.comments == row.comments;
          })
        ) {
          console.log("走了", row);
          this.haveTableData.push(row);
          // this.haveTableData = selection
        } else {
          //   this.haveTableData = this.haveTableData.filter((item) => {
          //   return !this.allTableData.some((row) => {
          //     return row.id == item.id;
          //   });
          // });
        
          this.haveTableData = this.haveTableData.filter((item) => {
            return row.comments != item.comments;
          });
          console.log("走了1", this.haveTableData);
        }
      } else {
        this.haveTableData = this.haveTableData.filter((item) => {
          return row.comments != item.comments;
        });
      }
    },
    selectAll(selection) {
      if (selection.length) {
        const newSelected = selection.filter(item =>!this.haveTableData.some(oldItem => oldItem.comments === item.comments));
      this.haveTableData = [...this.haveTableData, ...newSelected];
        
      } else {
        this.haveTableData = this.haveTableData.filter((item) => {
          return !this.tableList.some((row) => {
            return row.comments == item.comments;
          });
        });
      }
    },
      // 核心排序逻辑
    doSort() {
      return this.tableList.slice().sort((a, b) => {
        // 空值处理（null视为无限大）
        const aVal = a.sortOrder === null ? Infinity : a.sortOrder
        const bVal = b.sortOrder === null ? Infinity : b.sortOrder
        
        // 一级排序：用户输入的排序号
        const primarySort = aVal - bVal
        
        // 二级排序：原始顺序（保持稳定性）
        return
      })
    },

    // 输入完成处理（带防抖）
    handleSortInput: debounce(function(value) {
      this.validateInputs()
      this.forceTableRefresh()
    }, 300),

    // 输入框失焦处理
    handleBlur() {
      this.validateInputs()
      this.forceTableRefresh()
    },

    // 强制刷新表格
    forceTableRefresh() {
      this.tableVersion += 1
    },

    // 数据校验（确保最小值和唯一性）
    validateInputs() {
      const values = new Set()
      
      this.classInforList.forEach(item => {
        // 空值跳过检查
        if (item.sortOrder === null) return

        // 最小值校验
        if (item.sortOrder < 1) {
          this.$nextTick(() => {
            item.sortOrder = null
          })
          return
        }

        // 重复值校验
        if (values.has(item.sortOrder)) {
          this.$message.warning(`排序号 ${item.sortOrder} 重复，请修改`)
          this.$nextTick(() => {
            item.sortOrder = null
          })
        } else {
          values.add(item.sortOrder)
        }
      })
    },

    // 处理ElementUI自带的排序
    handleSortChange({ column, prop, order }) {
      console.log('表格排序变化:', order)
  },

  }
};
</script>

<style>
</style>